/**
 * 明细分类账建账 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.Init.InitDetailMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 75,
        header: false,
        collapsible: true,
        collapseMode: "mini",
        border: 0,
        layout: {
          type: "table",
          columns: 5
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        border: 0,
        ...PSI.Const.BODY_PADDING,
        items: [{
          region: "north",
          height: 30,
          border: 0,
          id: me.buildId(me, "panelInfo"),
        }, {
          region: "center",
          layout: "fit",
          border: 0,
          items: me.getMainGrid()
        }, {
          region: "south",
          layout: "fit",
          height: 300,
          border: 0,
          split: true,
          collapsible: true,
          collapseMode: "mini",
          header: false,
          items: me.getDetailGrid()
        }]
      }]
    });

    me.callParent(arguments);

    me.panelQueryCmp = PCL.getCmp(me.buildId(me, "panelQueryCmp"));
    me.buttonEdit = PCL.getCmp(me.buildId(me, "buttonEdit"));
    me.buttonCommit = PCL.getCmp(me.buildId(me, "buttonCommit"));
    me.buttonCancel = PCL.getCmp(me.buildId(me, "buttonCancel"));

    me.editQueryOrg = PCL.getCmp(me.buildId(me, "editQueryOrg"));

    me.panelInfo = PCL.getCmp(me.buildId(me, "panelInfo"));

    // AFX: 查询控件input List
    me.__editorList = [
      me.editQueryOrg,
    ];

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = me.panelQueryCmp;
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    me.queryCompanyList();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    let result = [{
      id: me.buildId(me, "buttonEdit"),
      iconCls: "PSI-tb-new",
      text: "录入明细分类账期末数据",
      ...PSI.Const.BTN_STYLE,
      handler: me._onEdit,
      scope: me
    }, "-", {
      id: me.buildId(me, "buttonCommit"),
      text: "完成明细分类账建账",
      ...PSI.Const.BTN_STYLE,
      handler: me._onCommit,
      scope: me,
      tooltip: me.buildTooltip("标记明细分类账建账工作完毕，此后不能录入建账数据"),
    }, {
      id: me.buildId(me, "buttonCancel"),
      text: "取消明细分类账建账",
      ...PSI.Const.BTN_STYLE,
      handler: me._onCancel,
      scope: me,
      tooltip: me.buildTooltip("取消建账完成标志，以便重新录入建账数据"),
    }, "-"];

    // 指南
    // 关闭
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("/Home/Help/index?t=accInit"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    });

    result = result.concat(me.getShortcutCmp());

    return result;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
  * 查询条件
  * 
  * @private
  */
  getQueryCmp() {
    const me = this;

    const modelName = me.buildModelName(me, "QueryOrg");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:5px;color:#595959;display:inline-block'>明细分类账建账</h2>
            &nbsp;&nbsp;<span style='color:#8c8c8c'>初始化明细分类账的建账数据</span>
            <div style='float:right;display:inline-block;margin:0px 0px 0px 20px;border-left:1px solid #e5e6e8;height:32px'>&nbsp;</div>
            `
    }, {
      id: me.buildId(me, "editQueryOrg"),
      labelWidth: 70,
      width: 440,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "组织机构",
      margin: "10, 0, 0, 0",
      xtype: "combobox",
      queryMode: "local",
      editable: false,
      valueField: "id",
      displayField: "name",
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        },
        select: {
          fn: me._onComboOrgSelect,
          scope: me
        },
      },
      colspan: 2,
    }, {
      xtype: "container",
      colspan: 2,
      items: [{
        xtype: "button",
        text: "刷新",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "10 0 0 10",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "10 0 0 20",
        handler() {
          me.panelQueryCmp.collapse();
        },
        scope: me
      }]
    },];
  },

  /**
   * @private
   */
  setPanelInfo() {
    const me = this;
    me.panelInfo.getEl().setHTML("");

    const store = me.editQueryOrg.getStore();
    const companyId = me.editQueryOrg.getValue();
    const org = store.getById(companyId);
    let name = org?.get("name");
    if (!name) {
      name = "";
    }

    me.ajax({
      url: me.URL("SLN0002/Init/queryInitStatus"),
      params: {
        companyId,
      },
      callback(options, success, response) {
        const data = me.decodeJSON(response.responseText);
        if (data.year) {
          const ym = `建账会计期间:${data.year}年${data.month}月，`;

          const inited = parseInt(data.detailInited) == 1;

          me._inited = inited;

          let s = "";
          if (inited) {
            const dt = data.detailDT;
            s = `于${dt}完成明细分类账建账`;
          } else {
            s = `<span style='color:red'>尚未完成明细分类账建账</span>`;
          }

          const result = `<h3 style='margin-left:5px;margin-top:5px;color:#595959;display:inline-block'>
                            <span style='color:#003eb3'>${name}</span>
                            ${ym}${s}
                          </h3>`;

          me.panelInfo.getEl().setHTML(result);
        } else {
          const result = `<h3 style='margin-left:5px;margin-top:5px;color:#595959;display:inline-block'>
            <span style='color:#003eb3'>${name}</span> -
            <span style='color:brown'>尚未录入明细分类账建账数据</span>
          </h3>`;
          me.panelInfo.getEl().setHTML(result);
          me._inited = false;
        }

        me.setButtonsStatus();
      }
    });
  },

  /**
   * @private
   */
  setButtonsStatus() {
    const me = this;

    if (me._inited) {
      me.buttonCommit.setDisabled(true);
      me.buttonEdit.setDisabled(true);
      me.buttonCancel.setDisabled(false);
    } else {
      me.buttonCommit.setDisabled(false);
      me.buttonEdit.setDisabled(false);
      me.buttonCancel.setDisabled(true);
    }
  },

  /**
   * @private
   */
  queryCompanyList() {
    const me = this;
    const store = me.editQueryOrg.getStore();
    const r = {
      url: me.URL("SLN0002/Init/companyList"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            me.editQueryOrg.setValue(data[0]["id"]);

            me.setPanelInfo();
            me.refreshMainGrid();
          }
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;

    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "AccMain");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "subject", "leaf", "children", "debit", "credit", "balance", "balanceDir"]
    });

    const store = PCL.create("PCL.data.TreeStore", {
      model: modelName,
      // autoLoad: false,
      // root: {
      //   expand: false,
      // },
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0002/Init/queryAccDetailData"),
      },
      listeners: {
        beforeload: {
          fn() {
            PCL.apply(store.proxy.extraParams, {
              companyId: me.editQueryOrg?.getValue(),
            });
          },
          scope: me
        }
      },
    });

    me._mainGrid = PCL.create("PCL.tree.Panel", {
      cls: "PSI",
      header: false,
      store,
      rootVisible: false,
      useArrows: true,
      viewConfig: {
        enableTextSelection: true,
      },
      columns: {
        defaults: {
          sortable: false,
          menuDisabled: true,
          draggable: false
        },
        items: [{
          xtype: "treecolumn",
          text: "科目",
          dataIndex: "subject",
          width: 500
        }, {
          text: "借方金额",
          dataIndex: "debit",
          width: 120,
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        }, {
          text: "贷方金额",
          dataIndex: "credit",
          width: 120,
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        }, {
          text: "余额",
          dataIndex: "balance",
          width: 120,
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        }, {
          text: "余额方向",
          dataIndex: "balanceDir",
          width: 90,
          align: "center",
        },]
      },
      listeners: {
        select: {
          fn: me._onMainGridSelect,
          scope: me,
        }
      }
    });

    return me._mainGrid;
  },

  /**
   * @private
   */
  _onMainGridSelect(rowModel, record) {
    const me = this;
    const companyId = me.editQueryOrg.getValue();
    const subjectCode = record.get("id");

    const grid = me.getDetailGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0002/Init/queryFmtColsForDetailAcc"),
      params: {
        companyId,
        subjectCode,
      },
      callback(options, success, response) {
        el?.unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          me._fmtCols = data;
          me._selectedSubjectCode = subjectCode;

          me.reconfigDetailGrid();
          me.queryAccDetailData();
        }
      }
    });
  },

  /**
   * @private
   */
  reconfigDetailGrid() {
    const me = this;

    const fields = [];
    const cols = [PCL.create("PCL.grid.RowNumberer", {
      text: "#",
      width: 40
    })];

    me._fmtCols.forEach((col) => {
      fields.push(col.fieldName);

      const c = {
        dataIndex: col.fieldName,
        header: col.caption,
        width: col.colWidth,
      }

      if (col.fieldName == "voucher_dt") {
        PCL.apply(c, {
          header: "期末日期",
        });
      }

      if (col.fieldName == "acc_db" || col.fieldName == "acc_cr" || col.fieldName == "acc_balance"
        || col.fieldName == "x_db_price" || col.fieldName == "x_cr_price" || col.fieldName == "x_balance_price"
      ) {
        PCL.apply(c, {
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        });
      }

      if (col.fieldName == "x_db_cnt" || col.fieldName == "x_cr_cnt" || col.fieldName == "x_balance_cnt") {
        PCL.apply(c, {
          align: "right",
        });
      }

      cols.push(c);
    });

    const modelName = me.buildModelName(me, "AccDetail");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields,
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me.getDetailGrid().reconfigure(store, cols);
  },

  /**
   * @private
   */
  queryAccDetailData() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    const subjectCode = me._selectedSubjectCode;

    const grid = me.getDetailGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0002/Init/queryDataForDetailAcc"),
      params: {
        companyId,
        subjectCode,
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }

        el?.unmask();
      }
    });
  },

  /**
   * @private
   */
  getDetailGrid() {
    const me = this;

    if (me._detailGrid) {
      return me._detailGrid;
    }

    const modelName = me.buildModelName(me, "AccDetail");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "subject", "debit", "credit", "balance", "balanceDir"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._detailGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [PCL.create("PCL.grid.RowNumberer", {
          text: "#",
          width: 40
        }), {
          header: "科目",
          dataIndex: "subjectCode"
        }]
      },
      store,
    });

    return me._detailGrid;
  },

  /**
   * @private
   */
  _onComboOrgSelect() {
    const me = this;

    me.setPanelInfo();

    me.refreshMainGrid();
  },

  /**
   * @private
   */
  refreshMainGrid() {
    const me = this;

    me.getDetailGrid().getStore().removeAll();

    me.getMainGrid().getStore().reload();
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;

    me.refreshMainGrid();
  },

  /**
   * @private
   */
  _onEdit() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const company = store.getById(companyId);

    const form = PCL.create("PSI.SLN0002.Init.DetailEditForm", {
      companyId,
      companyName: company.get("name"),
      parentForm: me,
    });
    form.show();
  },

  /**
   * @private
   */
  _onCommit() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    let name = org?.get("name");
    if (!name) {
      name = "";
    }

    const info = `当前组织机构：<span style='color:red'>${name}</span>
                  <br/>
                  请确认是否标记明细分类账建账完毕？`;
    const confirmFunc = () => {
      const el = PCL.getBody();
      el.mask("正在操作中...");

      const r = {
        url: me.URL("SLN0002/Init/commitAccDetailInit"),
        params: {
          companyId,
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.showInfo("成功完成建账操作");
              me.setPanelInfo();
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };
    me.confirm(info, confirmFunc);
  },
  /**
   * @private
   */
  _onCancel() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    let name = org?.get("name");
    if (!name) {
      name = "";
    }

    const info = `当前组织机构：<span style='color:red'>${name}</span>
                  <br/>
                  请确认是否取消明细分类账建账？`;
    const confirmFunc = () => {
      const el = PCL.getBody();
      el.mask("正在操作中...");

      const r = {
        url: me.URL("SLN0002/Init/cancelAccDetailInit"),
        params: {
          companyId,
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.showInfo("成功完成取消操作");
              me.setPanelInfo();
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };
    me.confirm(info, confirmFunc);
  },
});
